# coding=utf8
import os
import time

os.environ['TZ'] = 'GMT-8'
time.tzset()


def get_day_start_and_end(offset_day=0):
    ts = time.time() + offset_day * 24 * 60 * 60
    t = time.localtime(ts)
    tt = time.localtime(ts + 24 * 60 * 60)
    start_time = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', t), '%Y-%m-%d %H:%M:%S'))
    end_time = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00', tt), '%Y-%m-%d %H:%M:%S'))
    return int(start_time), int(end_time)


def str_to_time(ori_str, str_format="%Y-%m-%d %H:%M:%S"):
    time_arr = time.strptime(ori_str, str_format)
    return int(time.mktime(time_arr))


def time_to_str(str_format="%Y-%m-%d %H:%M:%S", unixtime=time.time()):
    time_arr = time.localtime(unixtime)
    return time.strftime(str_format, time_arr)


def get_root_path(sub='/'):
    path = os.path.split(os.path.realpath(__file__))[0]
    return os.path.realpath(path + '/../' + sub) + '/'


def get_pic_from_url(url):
    from io import BytesIO
    import requests

    r = requests.get(url)
    return BytesIO(r.content)


def make_res(code=200, msg='success', item=None):
    res = {'info': {
        'code': code,
        'codeMessage': msg
    }}
    if item:
        res['item'] = item

    return res


def enblowfish(keyword):
    from Crypto.Cipher import Blowfish
    from Crypto import Random
    from struct import pack
    # 兼容python3.4
    import binascii

    bs = Blowfish.block_size
    key = b'3Y7W8G57JZK1D8SYIL53UN'
    iv = Random.new().read(bs)
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    plaintext = keyword.encode()
    plen = bs - divmod(len(plaintext), bs)[1]
    padding = [plen] * plen
    padding = pack('b' * plen, *padding)
    return str(binascii.hexlify(iv + cipher.encrypt(plaintext + padding)), 'ascii')


def deblowfish(encrypto_str):
    from Crypto.Cipher import Blowfish
    try:
        encrypto_bytes = bytes.fromhex(encrypto_str)
        key = b'3Y7W8G57JZK1D8SYIL53UN'
        bs = Blowfish.block_size
        iv = encrypto_bytes[:bs]
        cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
        decode_str = cipher.decrypt(encrypto_bytes[bs:])
        padding = int(decode_str[-1])
    except:
        return ''
    return decode_str[:-padding].decode()


def random_char(size=6, special=False):
    import random
    import string
    chars = string.ascii_letters + string.digits
    if special:
        chars += '!@#$%^&*'
    return ''.join(random.choice(chars) for _ in range(size))


def split_list(long_list, chunk_size):
    import itertools
    for small in itertools.zip_longest(*[iter(long_list)] * chunk_size):
        yield small
